package com.zy.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.gmall.realtime.app.func.BeanToJsonStrFunction;
import com.zy.gmall.realtime.bean.TrafficHomeDetailPageViewBean;
import com.zy.gmall.realtime.util.DateFormatUtil;
import com.zy.gmall.realtime.util.DorisUtil;
import com.zy.gmall.realtime.util.KafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.doris.flink.sink.DorisSink;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class DwsTrafficHomeDetailPageViewWindow{
    public static void main(String[] args) {
        //从 Kafka页面日志主题读取数据，统计当日的首页和商品详情页独立访客数。

        //1 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
        //2 检查点
        env.enableCheckpointing(10000L);
        //3 数据源
            //设置消费主题 和 组
            String topic = "topic_pages";
            String groupId = "test";
        KafkaSource<String> kafkaSource = KafkaUtil.getKafkaSource(topic, groupId);
        DataStreamSource<String> sourceDs = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource");
        //4 转换JSONObj
        SingleOutputStreamOperator<JSONObject> mapDs = sourceDs.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String s) throws Exception {
                return JSON.parseObject(s);
            }
        });
        //5 过滤
        SingleOutputStreamOperator<JSONObject> filterDs = mapDs.filter(new FilterFunction<JSONObject>() {
            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {
                String pageId = jsonObject.getJSONObject("page").getString("page_id");
                return pageId.equals("home") || pageId.equals("good_detail");
            }
        });
        //filterDs.print(">>>>>>");
        //6 设置水位线
        SingleOutputStreamOperator<JSONObject> watermarksDs = filterDs.assignTimestampsAndWatermarks(
                WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject jsonObject, long l) {
                                        return jsonObject.getLong("ts");
                                    }
                                }
                        )
        );
        //7 分组
        KeyedStream<JSONObject, String> keyedDs = watermarksDs.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getJSONObject("common").getString("mid");
            }
        });
        //8 转换为实体类(窗口开启 关闭 分区时间 home1 good_detail_1)，并判断是否是独立用户
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> processDs = keyedDs.process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
            //设置状态  用于判断是否是首次   或者  状态有但是不是今天
            private ValueState<String> homeState;
            private ValueState<String> detailState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //初始化
                ValueStateDescriptor<String> homeStateDescriptor = new ValueStateDescriptor<>("homeState", String.class);
                //homeStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(org.apache.flink.api.common.time.Time.days(1)).build());
                ValueStateDescriptor<String> detailStateDescriptor = new ValueStateDescriptor<>("homeState", String.class);
                homeState = getRuntimeContext().getState(homeStateDescriptor);
                detailState = getRuntimeContext().getState(detailStateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>.Context context, Collector<TrafficHomeDetailPageViewBean> collector) throws Exception {
                //home

                String lastHomeState = homeState.value();
                Long ts = jsonObject.getLong("ts");
                String visitTime = DateFormatUtil.toDate(ts);
                Long homeUvCt = 0L;
                Long goodDetailUvCt = 0L;
                //当然要分开啦home 和 detail   同一个属性怎么能一起存在呢
                if ("home".equals(jsonObject.getJSONObject("page").getString("page_id"))){
                    if (StringUtils.isEmpty(lastHomeState) || StringUtils.isNotEmpty(lastHomeState) && lastHomeState.equals(visitTime)) {
                        // 判断状态是否为空 或者是不为空，但是和当前日期不一样  说明是第一次给 1
                        homeUvCt = 1L;
                        //时间更新到状态里
                        homeState.update(visitTime);
                    }
                }else {
                    // detail
                    String detailDate = detailState.value();
                    if (StringUtils.isEmpty(detailDate) || StringUtils.isNotEmpty(detailDate) && detailDate.equals(visitTime)) {
                        goodDetailUvCt = 1L;
                        detailState.update(visitTime);
                    }
                }

                if (homeUvCt != 0 || goodDetailUvCt != 0) {
                    collector.collect(new TrafficHomeDetailPageViewBean(
                            "", "", "", homeUvCt, goodDetailUvCt
                    ));
                }
            }
        });

        //processDs.print(">>>>>>");
        //9 开窗
        AllWindowedStream<TrafficHomeDetailPageViewBean, TimeWindow> windowedDs
                = processDs.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)));//滚动事件时间
        //10 聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> reduceDs = windowedDs.reduce(
                new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean t1, TrafficHomeDetailPageViewBean t2) throws Exception {
                        t1.setHomeUvCt(t1.getHomeUvCt() + t2.getHomeUvCt());
                        t1.setGoodDetailUvCt(t1.getGoodDetailUvCt() + t2.getGoodDetailUvCt());
                        return t1;
                    }
                }
                ,
                new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>.Context context, Iterable<TrafficHomeDetailPageViewBean> iterable, Collector<TrafficHomeDetailPageViewBean> collector) throws Exception {
                        long start = context.window().getStart();
                        long end = context.window().getEnd();
                        for (TrafficHomeDetailPageViewBean viewBean : iterable) {
                            viewBean.setStt(DateFormatUtil.toYmdHms(start));
                            viewBean.setEdt(DateFormatUtil.toYmdHms(end));
                            viewBean.setCurDate(DateFormatUtil.toDate(start));
                            collector.collect(viewBean);
                        }
                    }
                }
        );

        //reduceDs.print(">>>>>>>");
        //11 写入doris
        reduceDs.map(
                new BeanToJsonStrFunction<>()
        ).sinkTo(DorisUtil.getDorisSink("dws_traffic_home_detail_page_view_window"));

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
